package cn.evun.tms.generator.task;

import cn.evun.tms.generator.Constants;
import cn.evun.tms.generator.config.Configuration;
import cn.evun.tms.generator.framework.AbstractApplicationTask;
import cn.evun.tms.generator.framework.context.ApplicationContext;
import cn.evun.tms.generator.handler.BaseHandler;
import cn.evun.tms.generator.handler.impl.DaoHandler;
import cn.evun.tms.generator.model.DaoInfo;
import cn.evun.tms.generator.model.MapperInfo;
import cn.evun.tms.generator.model.ServiceInfo;

import java.util.ArrayList;
import java.util.List;

public class DaoTask extends AbstractApplicationTask {

	private static String DAO_FTL = "template/Dao.ftl";

	private List<DaoInfo> daoInfos;

	@SuppressWarnings("unchecked")
	@Override
	protected boolean doInternal(ApplicationContext context) throws Exception {
		logger.info("开始生成dao");

		daoInfos = (List<DaoInfo>) context.getAttribute("daoList");

		BaseHandler<DaoInfo> handler = null;
		for (DaoInfo daoInfo : daoInfos) {
			handler = new DaoHandler(DAO_FTL, daoInfo);
			handler.execute(context);
		}

		logger.info("生成dao完成");
		return false;
	}

	@Override
	protected void doAfter(ApplicationContext context) throws Exception {
		super.doAfter(context);

		List<MapperInfo> mapperInfos = new ArrayList<MapperInfo>();
		List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>();
		MapperInfo mapperInfo = null;
		ServiceInfo serviceInfo = null;
		for (DaoInfo daoInfo : daoInfos) {
			mapperInfo = new MapperInfo();
			mapperInfo.setDaoInfo(daoInfo);
			mapperInfo.setEntityInfo(daoInfo.getEntityInfo());
			mapperInfo.setFileName(daoInfo.getEntityInfo().getEntityName() + Constants.MAPPER_XML_SUFFIX);
			mapperInfo.setNamespace(daoInfo.getPackageStr() + Constants.CHARACTER_POINT + daoInfo.getClassName());
			mapperInfos.add(mapperInfo);
			serviceInfo = new ServiceInfo();
			serviceInfo.setDaoInfo(daoInfo);
			serviceInfo.setEntityName(daoInfo.getEntityInfo().getEntityName());
			serviceInfo.setClassName(daoInfo.getEntityInfo().getClassName() + Constants.SERVICE_SUFFIX);
			serviceInfo.setEntityDesc(daoInfo.getEntityInfo().getEntityDesc());
			serviceInfo.setPackageStr(Configuration.getString("service.package"));
			serviceInfos.add(serviceInfo);
		}
		context.setAttribute("mapperInfos", mapperInfos);
		context.setAttribute("serviceInfos", serviceInfos);
	}

}
